package com.phpxiu.app.view.custom;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.phpxiu.app.adapter.EmotionPagerAdapter;
import com.phpxiu.app.emotion.EmotionIcon;
import com.phpxiu.app.emotion.People;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.presenters.viewinterface.C2CChatView;
import com.phpxiu.app.utils.KKYUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 聊天界面输入控件
 */
@Deprecated
public class ChatInput extends RelativeLayout implements TextWatcher,View.OnClickListener,EmotionPagerAdapter.OnEmotionInputCallBack {
    private static final String TAG = "ChatInput";
    private final int REQUEST_CODE_ASK_PERMISSIONS = 100;
    private boolean isSendVisible,isHoldVoiceBtn,isEmoticonReady;
    private InputMode inputMode = InputMode.NONE;
    private ImageButton btnAdd, btnVoice, btnKeyboard, btnEmotion;
    private Button btnSend;
    private EditText editText;
    private LinearLayout morePanel,textPanel;
    private TextView voicePanel;
    private LinearLayout emoticonPanel;
    private C2CChatView chatView;
    private ViewPager emotionPager;
    private EmotionPagerAdapter mAdapter;
    private CirclePageIndicator indicator;
    private List<List<EmotionIcon>>pagers=new ArrayList<List<EmotionIcon>>();
    public ChatInput(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.chat_input, this);
        initView();
    }

    private void initView(){
        textPanel = (LinearLayout) findViewById(R.id.text_panel);
        btnAdd = (ImageButton) findViewById(R.id.btn_add);
        btnAdd.setOnClickListener(this);
        btnSend = (Button) findViewById(R.id.btn_send);
        btnSend.setOnClickListener(this);
        btnVoice = (ImageButton) findViewById(R.id.btn_voice);
        btnVoice.setOnClickListener(this);
        btnEmotion = (ImageButton) findViewById(R.id.btnEmoticon);
        btnEmotion.setOnClickListener(this);
        morePanel = (LinearLayout) findViewById(R.id.morePanel);
        LinearLayout showGift = (LinearLayout) findViewById(R.id.show_inner_gift_panel);
        showGift.setOnClickListener(this);
        showOrHideSendBtn();
        findViewById(R.id.open_image_store).setOnClickListener(this);
        findViewById(R.id.open_image_camera).setOnClickListener(this);
        btnKeyboard = (ImageButton) findViewById(R.id.btn_keyboard);
        btnKeyboard.setOnClickListener(this);
        voicePanel = (TextView) findViewById(R.id.voice_panel);
        if(!CurLiveInfo.isInRoom){
            voicePanel.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            isHoldVoiceBtn = true;
                            updateVoiceView();
                            break;
                        case MotionEvent.ACTION_UP:
                            isHoldVoiceBtn = false;
                            updateVoiceView();
                            break;
                    }
                    return true;
                }
            });
        }else{
            Toast.makeText(getContext(),getContext().getString(R.string.voice_msg_disable),Toast.LENGTH_LONG).show();
        }
        editText = (EditText) findViewById(R.id.input);
        editText.addTextChangedListener(this);
        editText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    updateView(InputMode.TEXT);
                }else{
                    KKYUtil.log("聊天输入框失去瞧点");
                }
            }
        });
        isSendVisible = editText.getText().length() != 0;
        emoticonPanel = (LinearLayout) findViewById(R.id.emoticonPanel);
        emotionPager=(ViewPager)findViewById(R.id.chat_input_emotion_selector);
        indicator=(CirclePageIndicator)findViewById(R.id.chat_input_emotion_selector_indicator);
        mAdapter=new EmotionPagerAdapter(getContext(),pagers,this);
        emotionPager.setAdapter(mAdapter);
        indicator.setViewPager(emotionPager);
        post(new Runnable() {
            @Override
            public void run() {
                prepareEmoticon();
            }
        });
    }

    private void updateView(InputMode mode){
        if (mode == inputMode) return;
        leavingCurrentState();
        switch (inputMode = mode){
            case MORE:
                morePanel.setVisibility(VISIBLE);
                break;
            case TEXT:
                if (editText.requestFocus()){
                    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
                }
                break;
            case VOICE:
                voicePanel.setVisibility(VISIBLE);
                textPanel.setVisibility(GONE);
                btnVoice.setVisibility(GONE);
                btnKeyboard.setVisibility(VISIBLE);
                break;
            case EMOTICON:
                if (!isEmoticonReady) {
                    return;
                    //prepareEmoticon();
                }
                emoticonPanel.setVisibility(VISIBLE);
                break;
            case NONE:

                break;
        }
        if(mode!=InputMode.VOICE){
            if(btnVoice.getVisibility()!=VISIBLE){
                btnVoice.setVisibility(VISIBLE);
            }
            if(btnKeyboard.getVisibility()==VISIBLE){
                btnKeyboard.setVisibility(GONE);
            }
        }
    }

    private void leavingCurrentState(){
        KKYUtil.log("离开当前状态："+inputMode.name());
        switch (inputMode){
            case TEXT:
                View view = ((Activity) getContext()).getCurrentFocus();
                InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                editText.clearFocus();
                break;
            case MORE:
                morePanel.setVisibility(GONE);
                break;
            case VOICE:
                voicePanel.setVisibility(GONE);
                textPanel.setVisibility(VISIBLE);
                btnVoice.setVisibility(VISIBLE);
                btnKeyboard.setVisibility(GONE);
                break;
            case EMOTICON:
                emoticonPanel.setVisibility(GONE);
        }
    }

    /**
     * 更新语音发送状态
     */
    private void updateVoiceView(){
        if (isHoldVoiceBtn){
            voicePanel.setText(getResources().getString(R.string.ui_voice_send_title));
            chatView.startSendVoice();
        }else{
            voicePanel.setText(getResources().getString(R.string.ui_voice_record_title));
            chatView.endSendVoice();
        }
    }

    /**
     * 关联聊天界面逻辑
     */
    public void setChatView(C2CChatView chatView){
        this.chatView = chatView;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        isSendVisible = s!=null&&s.length()>0;
        showOrHideSendBtn();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onEmotionInput(EmotionIcon emotion) {
        if(emotion.isEmpty()){
            return;
        }
        if(emotion.isDEl()){
            int action = KeyEvent.ACTION_DOWN;
            int code = KeyEvent.KEYCODE_DEL;
            KeyEvent event = new KeyEvent(action,code);
            editText.onKeyDown(KeyEvent.KEYCODE_DEL, event);
            return;
        }
        int start=editText.getSelectionStart();
        editText.getText().insert(start,emotion.getEmotion());
    }

    private void showOrHideSendBtn(){
        if (isSendVisible){
            btnAdd.setVisibility(GONE);
            btnSend.setVisibility(VISIBLE);
        }else{
            btnAdd.setVisibility(VISIBLE);
            btnSend.setVisibility(GONE);
        }
    }

    /**
     * 解析表情
     */
    private void prepareEmoticon(){
        if (emoticonPanel == null) return;
        List<EmotionIcon>emotionIcons=new ArrayList<EmotionIcon>();
        for(EmotionIcon e: People.DATA){
            emotionIcons.add(e);
            if(emotionIcons.size()==184){
                break;
            }
        }
        /**
        for(EmotionIcon e: Objects.DATA){
            emotionIcons.add(e);
        }

        for(EmotionIcon e: Symbols.DATA){
            emotionIcons.add(e);
        }

        for(EmotionIcon e: Places.DATA){
            emotionIcons.add(e);
        }

        for(EmotionIcon e: Nature.DATA){
            emotionIcons.add(e);
        }
         */
        int count=emotionIcons.size();
        int pageSize=23;//每页显示23个，最后一个显示删除图标
        int moreCount=count%pageSize;//不足整页的页面表情个数
        if(moreCount!=0) {
            //不足整页，补足整页
            int emptyCount = pageSize - moreCount;//如某个只显示了11个表情，则需补充12个空表情补满整页显示（23-11）
            for (int i = 0; i < emptyCount; i++) {
                EmotionIcon empty = new EmotionIcon();
                empty.setEmpty(true);
                emotionIcons.add(empty);
            }
            count=emotionIcons.size();
        }
        int pageCount=count/pageSize;//页数
        emotionPager.setOffscreenPageLimit(pageCount);
        //分页
        for(int i=0;i<pageCount;i++){
            List<EmotionIcon>pager=emotionIcons.subList(i * 23, Math.min((i + 1) * 23, emotionIcons.size()));
            List<EmotionIcon>_pager=new ArrayList<EmotionIcon>();
            for (EmotionIcon e:pager){
                e.setDEl(false);
                e.setEmpty(false);
                _pager.add(e);
            }
            EmotionIcon del=new EmotionIcon();
            del.setDEl(true);
            _pager.add(del);
            pagers.add(_pager);
        }
        mAdapter.notifyDataSetChanged();
        //加载表情
        isEmoticonReady = true;
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        Activity activity = (Activity) getContext();
        int id = v.getId();
        if (id == R.id.btn_send){
            chatView.sendText();
        }
        if (id == R.id.btn_add){
            updateView(inputMode == InputMode.MORE ? InputMode.TEXT : InputMode.MORE);
        }
        if (id == R.id.show_inner_gift_panel){//
            Toast.makeText(getContext(),"显示礼物面板",Toast.LENGTH_LONG).show();
        }
        if (id == R.id.open_image_store){
            chatView.sendImage();
        }
        if (id == R.id.open_image_camera){
            chatView.sendPhoto();
        }
        if (id == R.id.btn_voice){
            if(activity!=null && requestAudio(activity)||requestStorage(activity)){
                updateView(InputMode.VOICE);
            }
        }
        if (id == R.id.btn_keyboard){
            updateView(InputMode.TEXT);
        }
        if (id == R.id.btnEmoticon){
            updateView(inputMode == InputMode.EMOTICON? InputMode.TEXT: InputMode.EMOTICON);
        }
    }

    /**
     * 获取输入框文字
     */
    public Editable getText(){
        return editText.getText();
    }

    /**
     * 设置输入框文字
     */
    public void setText(String text){
        editText.setText(text);
    }

    /**
     * 设置输入模式
     */
    public void setInputMode(InputMode mode){
        updateView(mode);
    }

    public enum InputMode{
        TEXT,
        VOICE,
        EMOTICON,
        MORE,
        VIDEO,
        NONE,
    }

    private boolean requestAudio(Activity activity){
        if (afterM()){
            int hasPermission = activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO);
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return false;
            }
        }
        return true;
    }

    private boolean requestStorage(Activity activity){
        if (afterM()){
            int hasPermission = activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (hasPermission != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);
                return false;
            }
        }
        return true;
    }

    private boolean afterM(){
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

}
